package com.qianbei.common.utilis;

import android.content.Context;
import android.hardware.Camera;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;

/**
 * Created by gml on 16/8/2.
 */
public class PerssionTool {


        /**
         * 判断摄像头是否可用
         * 主要针对6.0 之前的版本，现在主要是依靠try...catch... 报错信息，感觉不太好，
         * 以后有更好的方法的话可适当替换
         *
         * @return
         */
        public static boolean isCameraCanUse() {
            boolean canUse = true;
            Camera mCamera = null;
            try {
                mCamera = Camera.open();
                // setParameters 是针对魅族MX5 做的。MX5 通过Camera.open() 拿到的Camera
                // 对象不为null
                Camera.Parameters mParameters = mCamera.getParameters();
                mCamera.setParameters(mParameters);
            } catch (Exception e) {
                canUse = false;
            }
            if (mCamera != null) {
                mCamera.release();
            }
            return canUse;
    }


    /**
     * 获取是否有录音权限
     *
     * @param context
     * @return
     */
    public static boolean getMicrophoneAvailable(Context context) {
        boolean available = true;
        int frequency = 11025;
        int channelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_MONO;
        int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;

        int bufferSize = AudioRecord.getMinBufferSize(frequency, channelConfiguration, audioEncoding);
        AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,
                frequency, channelConfiguration,
                audioEncoding, bufferSize);
//        AudioRecord  audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, 0,
//                0, 0, 256);

        try {
            byte[] audiodata = new byte[bufferSize];
            audioRecord.startRecording();
            int readsize = audioRecord.read(audiodata, 0, bufferSize);


//System.out.println("readsize=================="+readsize);
            if (AudioRecord.ERROR_INVALID_OPERATION == readsize) {
                available = false;
                audioRecord.stop();
            }

        } catch (IllegalStateException e) {
            e.printStackTrace();
            available = false;
            if(audioRecord!=null) {
                audioRecord.stop();
            }
        } finally {
            if(audioRecord!=null){
                audioRecord.stop();
            }

        }

//        if (audioRecord.getRecordingState() != AudioRecord.RECORDSTATE_RECORDING) {
//            available =false;
//        }

//        if (available) {
//            Toast.makeText(this, "有这个权限", Toast.LENGTH_LONG).show();
//        } else {
//            Toast.makeText(this, "木有这个权限", Toast.LENGTH_LONG).show();
//        }
        return available;
    }




}
